package com.czxy.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        System.out.println("LoginFilter过滤到请求：  "+uri);

        //放行静态资源和登录页面
        if (uri.endsWith("/index.jsp")||uri.contains("/css/")||uri.contains("/img/"))  {
         filterChain.doFilter(request,servletResponse);
         return;
        }
        //放行userservlet并且是login方法
        String method = request.getParameter("method");
        if (uri.endsWith("userservlet")&&"login".endsWith(method)){
            filterChain.doFilter(request,servletResponse);
            return;
        }
        //判断是否登录，根据登录情况放行或不放行
        Object loginU = request.getSession().getAttribute("loginU");
        if (loginU!=null){
          filterChain.doFilter(request,servletResponse);
          return;
        }else {
            //未登录状态
            //重新定向到index.jsp
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
